import AppSettings from "@runtime/base/AppSettings";
import { ClientMessage } from "@runtime/generate/message/ClientMessage";
import WebSocketComponent from "@runtime/module/WebSocket/WebSocketComponent";
import AssetLoaderComponent from "@runtime/UnityEngineBridge/AssetLoaderComponent";
import { Ref, ref, WatchStopHandle } from "@vue/runtime-dom";
import { message, Result } from 'ant-design-vue';
import MessageCode from "./MessageCode";
import ObjectControllerCode from "./ObjectControllerCode";
import OrbitCameraComponent from "./OrbitCameraComponent";
import statComponen from "./StateCode";
import { ElMessageBox } from "element-plus";
import { log } from "console";

/**
 * 起始页
 */
export default class HomeContent {
    private static instance: HomeContent = new HomeContent();
    /**
     * 起始页
     */
    public static get Default(): HomeContent {
        return this.instance;
    }

    constructor() {
        window.addEventListener('unload', this.Dispose.bind(this));
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);

        for (const watchStopHandle of this.watchStopHandles) {
            watchStopHandle();
        }
        this.watchStopHandles.clear();
    }

    // 点击了视角获取的值
    public visualAngle: Ref<string> = ref('');
    // 漫游消息切换
    public roam: Ref<boolean> = ref(false);

    // 穿戴
    public isWearOk: Ref<boolean> = ref(false);
    public isWearHelmetOk: Ref<boolean> = ref(false);
    public isWearShoeOk: Ref<boolean> = ref(false);
    public isWearGogglesOk: Ref<boolean> = ref(false);
    public isWearGlove2Ok: Ref<boolean> = ref(false);
    public isWearGlove3Ok: Ref<boolean> = ref(false);

    // 存储进入的哪个模式
    public typeIndex: Ref<any> = ref();

    public Loaded: Ref<boolean> = ref(false);
    public ProjectData: Ref<Array<any>> = ref([]);

    private watchStopHandles: Array<WatchStopHandle> = [];

    public ProgressText: Ref<string> = ref('');
    public ProgressVal: Ref<number> = ref(0);
    //工单
    public ModuleShow: Ref<boolean> = ref(false);
    //提交按钮显隐控制
    public SubBut: Ref<boolean> = ref(true);

    //评价表
    public EvaluateShow: Ref<boolean> = ref(false);
    //诊断仪
    public DiagnosShow: Ref<boolean> = ref(false);
    // 读取故障码
    public ReadDefaultCode: Ref<boolean> = ref(false);
    // 故障码数据
    public DefaultCodeData: Ref<any> = ref([]);
    // 数据流
    public DataFlow: Ref<boolean> = ref(false);
    // 数据流数据
    public DataFlowData: Ref<any> = ref();
    //维修手册
    public ServiceShow: Ref<boolean> = ref(false);
    //修复故障界面
    public TrobiesShow: Ref<boolean> = ref(false);
    public TrobiesList: Ref<any> = ref([]);
    
    public WorksheetData: Ref<any> = ref([]);

    public ModeType: Ref<number> = ref(1);
    //视角数据
    public ViewData: Ref<Array<any>> = ref([]);
    //故障点数据
    public FaultPointData: Ref<any> = ref({});
    //菜单目录数据
    public MenuData: Ref<any> = ref({});
    //万用表状态
    public MulType: Ref<boolean> = ref(false);
    //万用表数据
    public MulData: Ref<any> = ref({});
    // 绝缘仪状态
    public insulationType: Ref<boolean> = ref(false);
    //绝缘仪数据
    public insulationData: Ref<any> = ref({});
    // 接地检测仪状态
    public GroundResistanceType: Ref<boolean> = ref(false);
    // 接地检测仪数据
    public GroundResistanceData: Ref<any> = ref({});
    // 数显推拉力计状态
    public PullAndPushDynamometerType: Ref<boolean> = ref(false);
    // 数显推拉力计数据
    public PullAndPushDynamometerData: Ref<any> = ref({});
    // 数显特斯拉计状态
    public TeslaMeterType: Ref<boolean> = ref(false);
    // 数显特斯拉计数据
    public TeslaMeterData: Ref<any> = ref({});
    // 毫欧表状态
    public MilliohmmeterType: Ref<boolean> = ref(false);
    // 毫欧表数据
    public MilliohmmeterData: Ref<any> = ref({});
    //视角显隐
    public ViewType: Ref<boolean> = ref(true);
    //选手报告单数据
    public PlayerReportData: Ref<any> = ref({});
    //工单添加项数据
    public WorkOrderAddItem: Ref<any> = ref([]);
    //更新故障现象
    public undateTroubles : Ref<any> = ref('');
    //更新故障可能原因
    public undateTrobRes: Ref<any> = ref('');
    //更新故障机理分析
    public updateAnalyse: Ref<any> = ref('');
    //更新检测项（过程）
    public updateProcess: Ref<any> = ref('');

    //端子信息状态
    public TiType: Ref<boolean> = ref(false);
    //端子信息数据
    public TiData: Ref<any> = ref({});
    //pdf指定打页面
    public PageString: Ref<any> = ref('');
    //鼠标标签内容
    public MouseLabel: Ref<string> = ref('');
    public MouseLabelX: Ref<string> = ref('0');
    public MouseLabelY: Ref<string> = ref('0');
    //获取缓存数据
    public ProductName: Ref<any> = ref()
    public UserName: Ref<any> = ref()
    // 获取倒计时时间
    public Duration: Ref<any> = ref()
    // 倒计时控制
    public timerControl: Ref<any> = ref()
    // 正计时控制
    public timekeepingControl: Ref<any> = ref()
    // 正计时时间
    public time: Ref<any> = ref("00:00:00")
    // 正计时成绩界面时间显示
    public timeShow: Ref<any> = ref("0时0分0秒")
    // 是否加载完成
    public isLoading: Ref<any> = ref(false)

    //存贮启动参数
    public CacheFullData: Ref<any> = ref()
    //存贮启动时间
    public StartTime: Ref<any> = ref()
    //工单类型
    public WOT: Ref<boolean> = ref(true);
    public BDT: Ref<string> = ref('0');
    //综合结果分析
    public Synthetical: Ref<any> = ref()
    // 雷达指示器
    public RadarIndicator: Ref<any> = ref([])
    // 雷达结果值
    public RadarResultValue: Ref<any> = ref([])
    // 总时间
    public AllTime: Ref<any> = ref()
    //故障修复记录
    public FaultRepair: Ref<any> = ref()
    //全量评价表数据
    public AED: Ref<any> = ref()
    //加速踏板数值
    public ACCELERATOR_PEDAL: Ref<any> = ref('0')
    //制动踏板数值
    public BRAKE_PEDAL: Ref<any> = ref('0')
    //方向盘数值
    public STEERING_WHEEL: Ref<any> = ref('0')
    // 空调风量值
    public WIND_VELOCITY: Ref<any> = ref('0')
    // 地图视图按钮
    public WindowViewType: Ref<boolean> = ref(false); 
    // 视角点
    public currentPoint: Ref<string> = ref('0'); 
    // 标签
    public tip: Ref<boolean> = ref(true); 

    // 控制弹窗显隐
    public popTypes: Ref<boolean> = ref(false); 
    public messageCodeResult: Ref<string> = ref(''); 
    // 评价表
    public ratingForm: Ref<any> = ref([])
    // 工单基本信息
    public workOrderSheet: Ref<any> = ref([])
    // public workOrderSheet: Ref<any> = ref({});
    // 评价表展示
    public showPingJia: Ref<boolean> = ref(false); 
    // 穿戴基本信息
    public wearInfo: Ref<any> = ref([])
    //工具栏信息
    public ToolInformation: Ref<any> = ref({});
    public Tool_Icon: Ref<any> = ref('');
    // 当前步骤
    public nowStep: Ref<any> = ref()
    public getAllStep: Ref<any> = ref()
    // 选择的故障数量
    public FaultNumber: Ref<any> = ref()
    // 车辆控制
    public vehicleControl: Ref<any> = ref([]);
    //数据监听
    public OnReceive(id: number, content: string): void {
        console.log(`${id} - ${content}`);
        if (this.IsJsonString(content)) {
            console.log(JSON.parse(content));
            if (id == MessageCode.Default.MsgCodesList.SYSTEM_LABEL) {
                this.MouseLabel.value = JSON.parse(content).Result
            }
            if (id == MessageCode.Default.MsgCodesList.DISASSEMBLY_OBJECT_MENU_SHOW) {
                this.MenuData.value = JSON.parse(content).Result
                WebSocketComponent.Default.PostMessage(new ClientMessage.DiagnosisDisplayUIMenuRequest(true))
            }
            if (id == MessageCode.Default.MsgCodesList.DIAGNOSTIC_MULTIMETER_USE) {
                console.log('打开万用表');
                this.MulData.value = JSON.parse(content).Result
                this.MulType.value = true
            }
            if (id == MessageCode.Default.MsgCodesList.INSULATIONMETER_USE) {
                console.log('打开绝缘表');
                this.insulationData.value = JSON.parse(content).Result
                this.insulationType.value = true                                  
            } 
            if (id == MessageCode.Default.MsgCodesList.GNDRESISTORMETER_USE) {
                console.log('打开接地表')
                this.GroundResistanceData.value = JSON.parse(content).Result
                this.GroundResistanceType.value = true                
            }
            if (id == MessageCode.Default.MsgCodesList.TESLAMETER_USE) {
                console.log('打开特斯拉计')
                this.TeslaMeterData.value = JSON.parse(content).Result
                this.TeslaMeterType.value = true             
            }
            if (id == MessageCode.Default.MsgCodesList.PULLPUSHDYNAMOMETER_USE) {
                console.log('打开推拉力计')
                this.PullAndPushDynamometerData.value = JSON.parse(content).Result
                this.PullAndPushDynamometerType.value = true                
            }
            if (id == MessageCode.Default.MsgCodesList.TESLAMETER_UPDATE) {
                // console.log('更新特斯拉计')
                this.TeslaMeterData.value = JSON.parse(content).Result
                console.log('更新特斯拉计数据: ',HomeContent.Default.TeslaMeterData.value);
            }
            if (id == MessageCode.Default.MsgCodesList.PULLPUSHDYNAMOMETER_UPDATE) {
                // console.log('更新推拉力计')
                this.PullAndPushDynamometerData.value = JSON.parse(content).Result
                console.log('更新推拉力计数据: ',HomeContent.Default.PullAndPushDynamometerData.value)
            }
            if (id == MessageCode.Default.MsgCodesList.INTERNALRESISTANCE_USE) {   
                console.log('打开毫欧表')
                this.MilliohmmeterData.value = JSON.parse(content).Result
                this.MilliohmmeterType.value = true                 
            }
            if (id == MessageCode.Default.MsgCodesList.INTERNALRESISTANCE_UPDATE) {   
                this.MilliohmmeterData.value = JSON.parse(content).Result
                console.log('更新毫欧表数据: ',HomeContent.Default.MilliohmmeterData.value)
            }
            if (id == MessageCode.Default.MsgCodesList.DIAGNOSTIC_MULTIMETER_UPDATE) {
                this.MulData.value = JSON.parse(content).Result
            } 
            if (id == MessageCode.Default.MsgCodesList.INSULATIONMETER_UPDATE) {
                this.insulationData.value = JSON.parse(content).Result
            } 
            if (id == MessageCode.Default.MsgCodesList.GNDRESISTORMETER_UPDATE) {
                this.GroundResistanceData.value = JSON.parse(content).Result
            } 
            if (id == MessageCode.Default.MsgCodesList.DIAGNOSTIC_ORDER_OPEN) {
                // console.log('20423DIAGNOSTIC_ORDER_GET_BASE_CONFIG');
                // this.PlayerReportData.value = JSON.parse(content).Result
                this.workOrderSheet.value = JSON.parse(content).Result
                // 打开工单
                HomeContent.Default.ModuleShow.value = true
            }
            if (id == MessageCode.Default.MsgCodesList.DIAGNOSTIC_DECODER_OPEN) {
                // 打开诊断仪
                HomeContent.Default.DiagnosShow.value = true
            }
            if (id == MessageCode.Default.MsgCodesList.INFORMATION_OPEN) {
                if (JSON.parse(content).Result != 0) {
                    this.PageString.value = `#page=${JSON.parse(content).Result}`
                } else {
                    this.PageString.value = ''
                }
                // 打开维修手册
                HomeContent.Default.ServiceShow.value = true
            } if (id == MessageCode.Default.MsgCodesList.DIAGNOSTIC_FAULT_REPAIR_OPEN) {
                // 打开修复故障界面
                this.TrobiesList.value = JSON.parse(content).Result
                this.TrobiesList.value.faultRepairModels.forEach((item: any) => {
                    item.types = false
                });
                HomeContent.Default.TrobiesShow.value = true
            } if (id == MessageCode.Default.MsgCodesList.DIAGNOSTIC_APPEARENCE_UPDATE_VIEW) {
                if (JSON.parse(content).Result[0].Id == ObjectControllerCode.Default.MsgCodesList.APPEARENCE_UI_BRAKE_PEDAL) {
                    this.BRAKE_PEDAL.value = JSON.parse(content).Result[0].Value
                }
                if(JSON.parse(content).Result[0].Id == ObjectControllerCode.Default.MsgCodesList.APPEARENCE_UI_ACCELERATOR_PEDAL){
                    this.ACCELERATOR_PEDAL.value = JSON.parse(content).Result[0].Value
                }
                if(JSON.parse(content).Result[0].Id == ObjectControllerCode.Default.MsgCodesList.APPEARENCE_UI_STEERING_WHEEL){
                    this.STEERING_WHEEL.value = JSON.parse(content).Result[0].Value
                }
                if(JSON.parse(content).Result[0].Id == ObjectControllerCode.Default.MsgCodesList.APPEARENCE_UI_AIR_VOLUME){
                    this.WIND_VELOCITY.value = JSON.parse(content).Result[0].Value
                }
                //UI更新现象
                JSON.parse(content).Result.forEach((item: any) => {
                    statComponen.Default.StatusConfigs.value.set(item.Id, item.Value)
                });
            } if (id == MessageCode.Default.MsgCodesList.DIAGNOSTIC_DEVICE_SHOW_TERMINAL_INFO) {
                //端子信息
                this.TiType.value = true
                this.TiData.value = JSON.parse(content).Result
            } if (id == MessageCode.Default.MsgCodesList.VIEW_CHANGE) {
                //切换视角
                let ValData = JSON.parse(content).Result
                if (HomeContent.Default.roam.value) {
                    HomeContent.Default.roam.value = false;
                    WebSocketComponent.Default.PostMessageAsync(
                      new ClientMessage.RoamModeRequest(HomeContent.Default.roam.value)
                    );
                  }
                OrbitCameraComponent.Default.UpdateV2Async(ValData.TargetContainer, ValData.Horizontal, ValData.Vertical, ValData.Distance, ValData.MinDistance, ValData.MaxDistance, ValData.VerticalAngleMax, ValData.VerticalAngleMin, 1, 1, 1, ValData.HorizontalAngleMax, ValData.HorizontalAngleMin);
            } if (id == MessageCode.Default.MsgCodesList.SYSTEM_WARNING) {  // 10007
                message.warning(JSON.parse(content).Result);
            } if(id == MessageCode.Default.MsgCodesList.SYSTEM_MESSAGE) {   // 10006
                this.popTypes.value = true
                HomeContent.Default.messageCodeResult = JSON.parse(content).Result
            }if (id == MessageCode.Default.MsgCodesList.VIEW_CHANGE_OBSERVE) {
                //切换视角
                let ValData = JSON.parse(content).Result
                if (HomeContent.Default.roam.value) {
                    HomeContent.Default.roam.value = false;
                    WebSocketComponent.Default.PostMessageAsync(
                      new ClientMessage.RoamModeRequest(HomeContent.Default.roam.value)
                    );
                  }
                WebSocketComponent.Default.PostMessageAsync(new ClientMessage.OrbitCameraUpdateAngleRequest(ValData.TargetContainer, ValData.Horizontal, ValData.Vertical, ValData.Distance, ValData.MinDistance, ValData.MaxDistance, ValData.VerticalAngleMax, ValData.VerticalAngleMin, ValData.VerticalAngleSpeed, ValData.DistanceSpeed, ValData.HorizontalAngleSpeed, ValData.HorizontalAngleMax, ValData.HorizontalAngleMin))
            } if (id == MessageCode.Default.MsgCodesList.TOOL_BAR_UPDATE) {
                // 工具栏
                this.ToolInformation.value = JSON.parse(content).Result
                console.log('工具路径：',JSON.parse(content).Result.Icon);
                
                // this.Tool_Icon.value = '/structure/' + JSON.parse(content).Result.Icon + '.png'
                this.Tool_Icon.value = '/images/工具栏/' + JSON.parse(content).Result.Icon + '.png'
            }
            if (id == MessageCode.Default.MsgCodesList.DIAGNOSTIC_STEP_VIEW_CONTENT) {
                // 步骤数据监听
                HomeContent.Default.nowStep.value = JSON.parse(content).Result
            }
        }
    }
    //判断类型
    IsJsonString(str: any) {
        try {
            JSON.parse(str);
        } catch (e) {
            return false;
        }
        return true;
    }

    public async Awake(): Promise<void> {
        this.Loaded.value = true;
        this.ProgressText.value = '系统初始化'
        this.ProgressVal.value = 25

        

        // 启动Unity
        // 资源编号R00029//R00050
        const configuration = JSON.stringify({
            LocalAddress: AppSettings.Default.LocalAddress,
            ShortName: 'P10087',
            Type: 1003,
        });

        await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.EmbeddedApplicationLaunchRequest('../EmbeddedApplication/Unity/Mix.Unity.exe', configuration));

        setTimeout(async () => {
            this.ProgressText.value = 'Unity启动中'
            this.ProgressVal.value = 30
        }, 800);
        setTimeout(async () => {
            this.ProgressText.value = '环境模块初始化'
            this.ProgressVal.value = 45
        }, 1600);
        // 获取Unity版本状态
        await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.EmbeddedApplicationVersionRequest());
        setTimeout(async () => {
            this.ProgressText.value = '获取Unity版本状态'
            this.ProgressVal.value = 60
        }, 2600);

        this.ProgressText.value = '系统资源初始化'
        let newArr: any = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.DiagnosisAdapterRequest(MessageCode.Default.MsgCodesList.SYSTEM_GET_ASSET))
        let AssetList: any[] = []
        JSON.parse(newArr.Content).Result.forEach((item: any) => {
            AssetList.push(item.Asset)
        });
        // this.ProgressText.value = '系统资源初始化'
        // await AssetLoaderComponent.Default.LoadAllAsync(AssetList);
        this.ProgressText.value = '视角模块初始化'
        setTimeout(async () => {
            this.ProgressVal.value = 70
        }, 2500);
        await AssetLoaderComponent.Default.LoadAllAsync(AssetList);

        let viewArr: any = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.DiagnosisAdapterRequest(MessageCode.Default.MsgCodesList.VIEW_DATA_CONFIG, '1'))
        let ValData = JSON.parse(viewArr.Content).Result
        await OrbitCameraComponent.Default.UpdateV2Async(ValData.TargetContainer, ValData.Horizontal, ValData.Vertical, ValData.Distance, ValData.MinDistance, ValData.MaxDistance, ValData.VerticalAngleMax, ValData.VerticalAngleMin, 1, 1, 1, ValData.HorizontalAngleMax, ValData.HorizontalAngleMin);
        // await OrbitCameraComponent.Default.UpdateV2Async('汽车维修4S店/整车模块', 1, 45, 2.0, 0.3, 3.0, 1, 1, 1);
    }

    public async Destroy(): Promise<void> {
    }
}
